package com.example.thread.basic;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 解决线程安全问题的方式三: Lock锁
 * 1. synchronized 与 Lock的异同?
 * 相同: 二者都可以解决线程安全问题
 * 不同: synchronized机制在执行完相应的同步代码以后，自动的释放同步监视器
 *      Lock需要手动的启动同步(Lock()),同时结束同步也需要手动的实现(unlock())
 * 2.优先使用顺序:
 * Lock -> 同步代码块(已经进入了方法体，分配相应资源) -> 同步方法(在方法体之外)
 *
 * @author readpage
 * @create 2022-08-04 22:54
 */
class Window3 implements Runnable {
    private int ticket = 50;

    //1.实力哈ReentrantLock
    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {
        while (true) {
            try {
                //2.调用锁定方法lock()
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + ":售票，票号为:" +ticket);
                    ticket--;
                } else {
                    break;
                }
            } finally {
                //3. 调用解锁的方法: unlock()
                lock.unlock();
            }
        }
    }
}
public class LockTest {
    public static void main(String[] args) {
        Window3 window3 = new Window3();

        Thread t1 = new Thread(window3);
        Thread t2 = new Thread(window3);
        Thread t3 = new Thread(window3);

        t1.setName("窗口1");
        t1.setName("窗口2");
        t1.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}
